package com.example.demo.filter;

import com.example.demo.constant.Constants;
import com.example.demo.header.HeaderMapRequestWrapper;
import com.example.demo.util.CookieUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author shipeilei
 * @date 2020-7-22 15:17:49
 * @desc desc
 */
@WebFilter(filterName = "SSOFilter", urlPatterns = "/*")
public class SSOFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        final HttpServletRequest request = (HttpServletRequest) servletRequest;
        HeaderMapRequestWrapper requestWrapper = new HeaderMapRequestWrapper(request);
        String authorization = requestWrapper.getHeader(Constants.HEADER_AUTHORIZATION_KEY);
        if (StringUtils.isEmpty(authorization)) {
            String token = CookieUtil.getCookieValue(request, Constants.COOKIE_TOKEN_KEY);
            if (!StringUtils.isEmpty(token)) {
                //模拟向Header中添加Bearer Token
                requestWrapper.addHeader(Constants.HEADER_AUTHORIZATION_KEY, Constants.BEARER_TYPE + " " + token);
            }
        }
        filterChain.doFilter(requestWrapper, servletResponse);
    }
}
